// orders.js
const app = getApp()
const { API } = require('../../../utils/api')

Page({
  data: {
    currentTab: 'pending',
    orders: [],
    filteredOrders: [],
    showCompleteModal: false,
    currentOrderId: '',
    currentOrderPrice: '',
    actualVolume: '',
    calculatedActualAmount: '',
    loading: false
  },

  onLoad() {
    this.loadOrders()
  },

  onShow() {
    this.loadOrders()
  },

  async loadOrders() {
    this.setData({ loading: true })
    
    try {
      // 调用后端API获取所有订单（管理员权限）
      const response = await API.getOrderList({
        page: 1,
        size: 1000, // 获取大量数据，实际项目中应该分页
        status: '' // 空字符串表示获取所有状态的订单
      })
      
      if (response && response.list) {
        this.setData({
          orders: response.list
        })
        this.filterOrders()
      }
    } catch (error) {
      console.error('获取订单列表失败:', error)
      wx.showToast({
        title: '获取订单失败',
        icon: 'error'
      })
      // 如果API调用失败，回退到本地存储
      this.loadOrdersFromLocal()
    } finally {
      this.setData({ loading: false })
    }
  },

  loadOrdersFromLocal() {
    const orders = wx.getStorageSync('fuelOrders') || []
    // 按创建时间倒序排列
    orders.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
    
    this.setData({
      orders: orders
    })
    this.filterOrders()
  },

  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({
      currentTab: tab
    })
    this.filterOrders()
  },

  filterOrders() {
    const { orders, currentTab } = this.data
    let filtered = orders

    if (currentTab !== 'all') {
      filtered = orders.filter(order => order.status === currentTab)
    }

    this.setData({
      filteredOrders: filtered
    })
  },



  completeOrder(e) {
    const orderId = e.currentTarget.dataset.id
    const order = this.data.orders.find(item => item.id === orderId)
    
    this.setData({
      showCompleteModal: true,
      currentOrderId: orderId,
      currentOrderPrice: order.fuelPrice,
      actualVolume: order.volume, // 默认使用预计升数
      calculatedActualAmount: ''
    })
    
    // 计算默认实际金额
    this.calculateActualAmount(order.volume, order.fuelPrice)
  },

  hideCompleteModal() {
    this.setData({
      showCompleteModal: false,
      currentOrderId: '',
      currentOrderPrice: '',
      actualVolume: '',
      calculatedActualAmount: ''
    })
  },

  onActualVolumeInput(e) {
    const volume = e.detail.value
    const order = this.data.orders.find(item => item.id === this.data.currentOrderId)
    
    this.setData({
      actualVolume: volume
    })
    
    if (volume && order) {
      this.calculateActualAmount(volume, order.fuelPrice)
    }
  },

  calculateActualAmount(volume, price) {
    if (volume && price) {
      const amount = (parseFloat(volume) * parseFloat(price)).toFixed(2)
      this.setData({
        calculatedActualAmount: amount
      })
    }
  },

  confirmComplete() {
    const { currentOrderId, actualVolume, calculatedActualAmount } = this.data
    
    if (!actualVolume) {
      wx.showToast({
        title: '请输入实际升数',
        icon: 'error'
      })
      return
    }

    const order = this.data.orders.find(item => item.id === currentOrderId)
    const actualAmount = calculatedActualAmount || (parseFloat(actualVolume) * parseFloat(order.fuelPrice)).toFixed(2)
    
    // 更新订单信息
    this.updateOrderComplete(currentOrderId, actualVolume, actualAmount)
    this.hideCompleteModal()
  },



  async updateOrderComplete(orderId, actualVolume, actualAmount) {
    try {
      // 调用后端API完成订单
      const response = await API.completeOrder({
        orderId: orderId,
        actualVolume: parseFloat(actualVolume),
        actualAmount: parseFloat(actualAmount)
      })
      
      if (response) {
        // 重新加载订单列表
        this.loadOrders()
        
        // 处理退款或补款逻辑
        const order = this.data.orders.find(item => item.id === orderId)
        if (order) {
          this.handlePaymentDifference({
            ...order,
            actualVolume: actualVolume,
            actualAmount: actualAmount
          })
        }
        
        wx.showToast({
          title: '订单完成',
          icon: 'success'
        })
      }
    } catch (error) {
      console.error('完成订单失败:', error)
      wx.showToast({
        title: '完成订单失败',
        icon: 'error'
      })
      
      // 如果API调用失败，回退到本地存储方式
      this.updateOrderCompleteLocal(orderId, actualVolume, actualAmount)
    }
  },

  updateOrderCompleteLocal(orderId, actualVolume, actualAmount) {
    let orders = wx.getStorageSync('fuelOrders') || []
    const orderIndex = orders.findIndex(item => item.id === orderId)
    
    if (orderIndex !== -1) {
      const order = orders[orderIndex]
      
      // 更新订单状态
      orders[orderIndex].status = 'completed'
      orders[orderIndex].actualVolume = actualVolume
      orders[orderIndex].actualAmount = actualAmount
      orders[orderIndex].completeTime = new Date().toISOString()
      orders[orderIndex].updateTime = new Date().toISOString()
      
      wx.setStorageSync('fuelOrders', orders)
      
      // 创建销售记录用于统计报表
      this.createSalesRecord(order, actualVolume, actualAmount)
      
      this.loadOrders()
      
      // 处理退款或补款逻辑
      this.handlePaymentDifference(orders[orderIndex])
      
      wx.showToast({
        title: '订单完成',
        icon: 'success'
      })
    }
  },

  createSalesRecord(order, actualVolume, actualAmount) {
    const record = {
      id: Date.now(),
      orderId: order.id,
      orderNo: order.orderNo,
      userId: order.userId,
      userName: order.userName,
      fuelType: order.fuelType,
      volume: parseFloat(actualVolume),
      amount: parseFloat(actualAmount),
      date: new Date().toISOString(),
      timestamp: Date.now()
    }

    // 获取现有记录
    let records = wx.getStorageSync('fuelRecords') || []
    records.unshift(record)
    
    // 只保留最近500条记录
    if (records.length > 500) {
      records = records.slice(0, 500)
    }
    
    wx.setStorageSync('fuelRecords', records)
  },

  handlePaymentDifference(order) {
    const prepaid = parseFloat(order.prepaidAmount)
    const actual = parseFloat(order.actualAmount)
    const difference = actual - prepaid
    
    if (Math.abs(difference) > 0.01) { // 差额大于1分钱
      const message = difference > 0 
        ? `用户需补款¥${difference.toFixed(2)}` 
        : `需退款给用户¥${Math.abs(difference).toFixed(2)}`
      
      wx.showModal({
        title: '金额差异提醒',
        content: message,
        showCancel: false
      })
    }
  },


})